package branch.feature.signin_and_signup

import android.app.Activity
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.LocationSource
import com.amap.api.maps.LocationSource.OnLocationChangedListener
import com.amap.api.maps.MapView
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.UiSettings
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.example.myapplication.R
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.text.SimpleDateFormat
import java.util.Date

// ref link: https://blog.csdn.net/mjh1667002013/article/details/136245372#:~:text=%E6%9C%AC%E6%96%87%E8%AF%A6%E7%BB%86%E4%BB%8B%E7%BB%8D%E4%BA%86%E5%9C%A8Android%E5%BA%94%E7%94%A8%E4%B8%AD%E5%A6%82%E4%BD%95%E9%80%9A%E8%BF%87%E9%AB%98%E5%BE%B7%E5%9C%B0%E5%9B%BEAPI%E8%BF%9B%E8%A1%8C%E5%88%9D%E5%A7%8B%E5%8C%96%E5%AE%9A%E4%BD%8D%EF%BC%8C%E8%AE%BE%E7%BD%AE%E5%AE%9A%E4%BD%8D%E8%93%9D%E7%82%B9%EF%BC%8C%E4%BB%A5%E5%8F%8A%E9%85%8D%E7%BD%AE%E5%BF%85%E8%A6%81%E7%9A%84%E6%9D%83%E9%99%90%E3%80%82,%E6%AD%A5%E9%AA%A4%E5%8C%85%E6%8B%AC%E5%9C%A8AndroidManifest.xml%E4%B8%AD%E5%A3%B0%E6%98%8E%E6%9C%8D%E5%8A%A1%E5%92%8C%E6%9D%83%E9%99%90%EF%BC%8C%E8%AE%BE%E7%BD%AE%E5%AE%9A%E4%BD%8D%E6%A0%B7%E5%BC%8F%EF%BC%8C%E5%AE%9E%E7%8E%B0LocationSource%E5%92%8CAMapLocationListener%E6%8E%A5%E5%8F%A3%EF%BC%8C%E4%BB%A5%E5%8F%8A%E5%A4%84%E7%90%86%E5%AE%9A%E4%BD%8D%E6%88%90%E5%8A%9F%E5%92%8C%E9%94%99%E8%AF%AF%E6%83%85%E5%86%B5%E3%80%82
class MainActivity : Activity() {
    // 地图视图
    private lateinit var mapView: MapView

    // 地图图层
    private var aMap: AMap? = null

    // 位置监听器
    private var locChangeListener: OnLocationChangedListener? = null

    // 定位客户端
    private var aMapLocationClient: AMapLocationClient? = null

    // 定位参数配置选项
    private lateinit var aMapLocationClientOption: AMapLocationClientOption

    // 判断是否第一次定位
    private var isFirstLoc = true

    // 当前定位
    private lateinit var currentLatLng: LatLng

    private var uiSettings: UiSettings? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_ss)
        initPermission()
        initView(savedInstanceState)
        useCase()
    }


    private fun initView(savedInstanceState: Bundle?) {
        // 高德隐私合规
        run {
            MapsInitializer.updatePrivacyShow(this, true, true)
            MapsInitializer.updatePrivacyAgree(this, true)
            AMapLocationClient.updatePrivacyAgree(this, true)
            AMapLocationClient.updatePrivacyShow(this, true, true)
        }
        mapView = findViewById(R.id.amap_view)
        mapView.onCreate(savedInstanceState)
        if (aMap == null) {
            aMap = mapView.map
        }

        aMap?.setLocationSource(object : LocationSource {
            override fun activate(listener: OnLocationChangedListener?) {
                locChangeListener = listener
                if (aMapLocationClient == null) {
                    // 初始化定位
                    try {
                        // 初始化定位参数
                        aMapLocationClientOption = AMapLocationClientOption()
                        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)

                    } catch (e: Exception) {
                        throw RuntimeException()
                    }
                }
            }

            override fun deactivate() {
                locChangeListener = null
                aMapLocationClient?.let {
                    it.stopLocation()
                    it.onDestroy()
                    aMapLocationClient = null
                }
            }

        })

        val myLocationStyle: MyLocationStyle = MyLocationStyle()
        // 设置定位模式
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE)
        // 只在连续定位模式下生效
        myLocationStyle.interval(2000)
        // 设置是否显示小蓝点
        myLocationStyle.showMyLocation(true)

        myLocationStyle.anchor(0.5f, 0.5f).myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW)

        aMap?.myLocationStyle = myLocationStyle
        aMap?.isMyLocationEnabled = true

        uiSettings = aMap?.uiSettings
        // 缩放按钮不显示
        uiSettings?.isZoomControlsEnabled = false
        // 指南针显示
        uiSettings?.isCompassEnabled = true
        // 高德地图的logo位置
        uiSettings?.logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT

        aMapLocationClient = AMapLocationClient(this)

        // 初始化定位参数
        aMapLocationClientOption = AMapLocationClientOption()
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
        aMapLocationClientOption.setNeedAddress(true)
        aMapLocationClientOption.setOnceLocation(false)
        aMapLocationClientOption.setWifiScan(true)
        aMapLocationClientOption.setInterval(2000)

        // 客户端很重要，是显示当前位置的入口
        aMapLocationClient?.setLocationListener { loc ->
            if (locChangeListener != null && loc != null) {
                if (loc?.errorCode == 0) {
                    loc.locationType
                    loc.latitude
                    loc.longitude
                    loc.accuracy
                    val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    val date = Date(loc.time)
                    df.format(date)
                    loc.address
                    loc.country
                    loc.province
                    loc.city
                    loc.district
                    loc.street
                    loc.streetNum
                    loc.cityCode
                    loc.adCode
                    loc.aoiName
                }
            }

            if (isFirstLoc) {
                // 移动位置，相机
                aMap?.moveCamera(CameraUpdateFactory.zoomTo(10f))
                val markerOptions = MarkerOptions()
                markerOptions.title("当前位置")
                markerOptions.visible(true)
                aMap?.addMarker(markerOptions)

                if (loc != null) {
                    currentLatLng = LatLng(loc.latitude, loc.longitude)
                }
                aMap?.moveCamera(CameraUpdateFactory.changeLatLng(currentLatLng))

                locChangeListener?.onLocationChanged(loc)
                isFirstLoc = false
            } else {
                Toast.makeText(this, "显示当前位置出错", Toast.LENGTH_SHORT)
            }
        }

        aMapLocationClient?.setLocationOption(aMapLocationClientOption)

        aMapLocationClient?.startLocation()
    }

    // 定位权限
    private fun initPermission() {
        XXPermissions.with(this)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.ACCESS_BACKGROUND_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        Toast.makeText(
                            applicationContext,
                            "获取部分权限成功，但部分权限未正常授予",
                            Toast.LENGTH_SHORT
                        ).show()
                        return
                    }
                }
            })
    }

    // 地图用例
    private fun useCase() {
        // 标记一个上海点
        run {
            val latLng = LatLng(31.042119, 121.410428)
            val marker: Marker? = aMap?.addMarker(
                MarkerOptions().position(latLng).title("测试点").snippet("这是测试内容")
                    // 替换marker的图标
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_tip_route))
                    .alpha(1.0f)
            )
        }
        // 创建多个marker
        run {
        }
        // 绘制自定义marker
        run {
            val latLng: LatLng = LatLng(41.041991, 121.409628)

            val markerOptions: MarkerOptions = MarkerOptions()

            markerOptions.position(latLng)
            markerOptions.title("测试2").snippet("我是自定义marker")
            markerOptions.draggable(true)
            // 设置marker平贴地图效果
            markerOptions.setFlat(false)
            aMap?.addMarker(markerOptions)
        }

        run {
            var current: Marker? = null
            var ismarkclicked = false
            ismarkclicked = true
            aMap?.setOnMapClickListener {
                if (!ismarkclicked) {
                    if (current?.isInfoWindowShown() == true) {
                        current?.hideInfoWindow()
                    }
                }
            }

            aMap?.setOnMarkerClickListener { marker ->
                current = marker
                false
            }
        }

        run {

        }
    }


    // 销毁地图
    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
    }

    // 重新绘制加载地图
    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }

    // 暂停地图的绘制
    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    // 保存地图当前的状态
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView.onSaveInstanceState(outState)
    }
}